//引入模块
const express = require("express");
//引入连接池
const pool = require("../util/pool.js");
const query = require("../util/query.js");

const Tree = require("../util/tree.js");
const response = require("./response");
const Token = require("../util/token");
const {camelSnakeJson} = require("../util/common");
const {camelSnake} = require("../util/common");

//创建空路由器
let router = express.Router();
//挂载路由
//=================================================
// 1.4. 分类功能
// 1.4.1. 获取分类信息接口
// 参数名	参数说明	备注
// 无参数
router.get("/category", async (req, res) => {
    //获取数据,无
    //建sql语句
    let sql = "select id,name,pid,img from goods_category ORDER BY sort ASC ";
    try {
        let result = await query(sql);
        if (result.length <= 0) {
            throw "没有数据";
        }

        let data = result;
        //商品分类的Tree结构
        let tree = new Tree(data);
        data = tree.getTree();
        res.send({code: 1, msg: "获取分类信息数据成功", data});
    } catch (error) {
        res.send({code: -1, msg: "Query异常:" + error});
        return;
    }
});

router.get("/category/options", async (req, res) => {
    //获取数据,无
    //建sql语句
    let sql = "select id as value , name as text,pid as parent_id from goods_category  ORDER BY sort ASC ";
    try {
        let result = await query(sql);
        if (result.length <= 0) {
            throw "没有数据";
        }

        let data = [];
        //商品分类的Optiond结构
        let parentCategory = result.filter(item => item.parent_id == 0)
        parentCategory.forEach(item => {
            item.children = result.filter(element => element.parent_id == item.value);
            data.push(item);
        });
        response.sendSuccess(res, data, "获取分类信息数据成功")
    } catch (error) {
        response.sendError(res, "Query异常,error:" + error)
        return;
    }
});


//==============================================
// 1.5. 商品功能
// 1.5.1. 根据分类编号获取对应的商品列表
// 参数名	       参数说明
// category_id	分类编号
router.get("/list", async (req, res) => {
    try {
        //获取数据：分类编号
        let category_id = req.query.category_id;
        category_id = parseInt(category_id) || 0;
        //获取数据：商品名
        // let name = req.query.name;
        // console.log(`/good/list中如何处理接收到的商品名参数：${name}，还没实现....`);
        //获取数据：起始页码，从1开始
        let pageIndex = parseInt(req.query.pageIndex);
        pageIndex = pageIndex ? pageIndex : 1;
        //获取数据：每页大小
        let pageSize = parseInt(req.query.pageSize);
        pageSize = pageSize ? pageSize : 10;
        //计算开始查询的值start
        let start = (pageIndex - 1) * pageSize;
        //建sql语句
        let sql1 = "select count(*) as count from v_goods "; // ";
        let sql2 = "select * from v_goods "; // ";
        if (category_id > 0) {
            sql1 += ` where category_id =  ${category_id}`;
            sql2 += ` where category_id =  ${category_id}`;
        }
        sql2 += ` ORDER BY id DESC LIMIT ${start},${pageSize} `
        let sql = `${sql1} ; ${sql2}`;
        //console.log(sql)  //调试输出
        //执行Query
        let result = await query(sql);
        //处理返回数据，（返回记录数量是0也是一种成功），响应对象
        let recordTotal = result[0][0]["count"]; //获取记录总数，第1个SQL语句的执行结果
        let pageTotal = Math.floor(recordTotal / pageSize) + 1; //计算总页数
        let data = result[1];//第2个SQL语句的执行结果
        res.send({
            code: 1,
            msg: `加载商品列表成功`,
            recordTotal,
            pageIndex,
            pageSize,
            pageTotal,
            data
        });
    } catch (error) {
        res.send({code: -1, msg: "Query异常,error:" + error});
    }
});

//===============================================
//1.5.2. 根据商品编号获取对应的商品详情
// 参数名	参数说明	备注
// id	商品编号
router.get("/detail", async (req, res) => {
    try {
        //获取数据
        let id = req.query.id;
        id = parseInt(id);
        //验证数据是否为空
        if (!id) {
            throw "商品编号不能为空";
        }
        //建SQL语句
        let sql = `SELECT * FROM v_goods WHERE id=${id}`;

        //执行Query
        let result = await query(sql);
        let data = [];
        if (result.length == 0) {
            throw "商品不存在";
        }
        //有对应编号的商品
        let goods = result[0];
        if (goods.status == 0) {
            throw "商品已下架";
        }
        //处理商品图片数据
        if (goods.album) {
            let domain = req.headers.host;
            let albumArray = goods.album.split("|"); //"a.png | bbbb.png"
            goods.album = [];
            albumArray.forEach((img, i) => {
                goods.album.push({id: i, img});
            });

            //正则表达式的搜索和替换。(待继续..............)
            //
            // let pattern = /<img src="(\\/static\\/.*?)"\\/>/;
            // let replacement = `<img src="${domain}\\1">`;
            // goods.content.replace(pattern, replacement);
        }
        data = goods;
        res.send({code: 1, msg: "商品详情获取成功", data});
    } catch (error) {
        res.send({code: -1, msg: "Query异常,error:" + error});
        return;
    }
});

// 1.5.3. 根据多个商品编号获取对应的商品详情 shopcart
// 参数名	参数说明	备注
// ids	商品编号字符串	(98,99)
router.get("/detail_list", async (req, res) => {
    try {
        //获取数据
        let ids = req.query.ids;
        //验证数据
        if (!ids) {
            throw("编号不能为空");
        }

        //执行SQL语句
        let sql = `select * from v_goods where status=1 AND id in (${ids}) ORDER BY id DESC`;
        let result = await query(sql);
        if (result.length == 0) {
            throw `商品不存在，编号为：${ids}`;
        }

        let data = result;
        res.send({code: 1, msg: "商品详情获取成功", data});
    } catch (error) {
        res.send({code: -1, msg: "Query异常,error:" + error});
        return;
    }
});

//===============================================
//3.删除商品 GET /delete   http://127.0.0.1:8080/product/delete?id=1
router.get("/delete", async (req, res) => {
    //是否已登录
    let user = req.session.user;
    if (!user) {
        res.send({code: 2, msg: "未登录"});
        return;
    }
    //获取数据
    let id = req.query.id;
    try {
        //验证数据
        if (!id) throw "商品编号不能为空";
        //执行SQL语句
        let sql = `DELETE FROM goods WHERE id = ${id}`;
        await query(sql);
        //响应返回
        res.send({code: 1, msg: `删除成功 ：id=${id}`});
    } catch (error) {
        res.send({code: -1, msg: `删除失败, 错误信息: ${error}`});
    }

});


//===============================================
//.修改商品 POST /update
router.post("/update", async (req, res) => {
    try {
        //获取数据，验证数据
        let goods = req.body;
        if (!goods.id) throw  `字段（id）不能为空`;
        if (!goods.category_id) throw  `字段（category_id）不能为空`;
        if (!goods.name) throw  `字段（name）不能为空`;

        //执行SQL语句 ，修改表中对应的数据
        let sql = "UPDATE goods SET ? WHERE id=?";
        await query(sql, [goods, goods.id]);
        res.send({code: 1, msg: "更新成功！", data: goods});
    } catch (error) {
        res.send({code: -1, msg: `更新失败！错误信息：${error}`});
    }
});

//==============================================================================
//以下是原学子商城的API，如果要实现我的商城的商品添加，查询接口，代码供参考..........
//===============================================================================
//4.商品添加 POST /add
router.post("/addGoods", (req, res) => {
    //1.1获取数据
    let product = req.body;
    //1.2验证各项数据是否为空
    //遍历对象的属性
    for (const key in product) {
        if (product[key] === undefined) {
            res.send(response.paramEx(`${key} required`))
            return;
        }
    }
    let token = req.headers.authorization
    let data = Token.verify(token);
    product["user_id"] = data.data.id

    //1.3执行SQL语句
    let sql = "INSERT INTO goods SET ?";
    pool.query(sql, [product], (err, result) => {
        if (err) {
            res.send({code: 301, msg: `add failed, err: ${err}`}); //throw err;
            return;
        }

        //如果数据插入成功，响应对象
        if (result.affectedRows > 0) {
            res.send(response.ok(`添加商品成功`));
        } else {
            res.send(response.serverEx(`添加商品失败 , err: ${err.sqlMessage}`));
        }
    });
});
//===============================================
//5.商品查询 GET /search  該接口功能歸到list接口了 代码实现思路可以参考学习

router.get("/search", (req, res) => {
    let retJson = {
        code: 200,
        msg: "search ok",
        recordCount: 0,
        pageSize: 9,
        pageCount: 0,
        pno: req.query.pno || 0,
        data: [], //
    };

    // let output = {
    //   count: 0,
    //   pageSize: 9,
    //   pageCount: 0,
    //   pno: req.query.pno || 0,
    //   data: [],
    // };
    let kw = req.query.kw || "";
    //"mac i5 128g"
    let kws = kw.split(" ");
    //[mac,i5,128g]

    kws.forEach((elem, i, arr) => {
        arr[i] = `title like '%${elem}%'`;
    });

    /*[
      title like '%mac%',
      title like '%i5%',
      title like '%128g%'
    ]*/
    //join(" and ");
    let where = kws.join(" and ");
    //"title like '%mac%' and title like '%i5%' and title like '%128g%'"
    var sql = `select *,(select md from xz_laptop_pic where laptop_id=lid limit 1) as md from xz_laptop where ${where}`;
    console.log(sql);
    query(sql, [])
        .then((result) => {
            retJson.count = result.length;
            retJson.pageCount = Math.ceil(retJson.count / retJson.pageSize);
            sql += ` limit ?,?`;
            return query(sql, [retJson.pageSize * retJson.pno, retJson.pageSize]);
        })
        .then((result) => {
            retJson.data = result;
            res.send(retJson);
        });
});

router.get("/seller/list", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    if (data.code != 1) {
        return res.send(response.serverEx(data.msg))
    }
    let userId = data.data.id
    let sql = `select id,name,\`desc\`,price,num,status,category_id,img from goods where user_id=${userId} order by create_time desc`
    query(sql, []).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

router.put("/seller/list", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id

    let body = req.body;
    try {
        for (let i in body) {
            let item = body[i]
            let id = item.id
            delete item.id
            let sql = `update goods set ? where user_id=${userId} and id=${id}`
            await query(sql, item).then(result => {
                console.log(result)
            });
        }
        res.send(response.ok("修改商品信息成功!"))
    } catch (e) {
        res.send(response.serverEx(e))
    }
})

router.delete("/seller/list", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let ids = req.body.join(",")
    let sql = `delete from goods where user_id=${userId} and id in (${ids})`
    query(sql, []).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })

})

router.post("/seller/onSell", (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let ids = req.body.join(",")
    let sql = `update goods set status=1 where user_id=${userId} and id in (${ids})`
    query(sql).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

router.post("/buyer/evaluate", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.body;
    body["buyer_id"] = userId
    body=camelSnakeJson(body)
    await query(`update user_order set status=4 where id=${body['order_id']}`)
    let sql = `insert into goods_evaluate set ?`
    await query(sql, body).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

router.get("/evaluate", async(req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.query;
    console.log(body)

    let sql = `select * from goods_evaluate where buyer_id=${userId} and goods_id=${body.goodsId}`
    await query(sql,[]).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

//==================================================
//导出路由器
module.exports = router;
